﻿using HardcoreGame.Common.Cores.Logic;
using HardcoreGame.Common.Systems;
using Microsoft.Xna.Framework;
using System.IO;
using Terraria;
using Terraria.Audio;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;

namespace HardcoreGame.Common.Players
{
    internal class AgePlayer : ModPlayer
    {
        public int _deathCheckTimer;
        public const int DeathCheckInterval = 60 * 300;
        public StaminaLogic Logic { get; internal set; }
        public int AgeInDays { get; private set; } = 18 * 48;
        public bool HasSetAge { get; private set; } = false;
        public bool _hasShownThisSession;

        public int CurrentAge => AgeInDays / 48;

        public void SetAge(int years)
        {
            AgeInDays = years * 48;
            HasSetAge = true;
        }
        public override void OnEnterWorld()
        {
            if (!HasSetAge && !_hasShownThisSession && Main.netMode != NetmodeID.Server)
            {
                ModContent.GetInstance<AgeUISystem>().ShowAgeSelection();
                _hasShownThisSession = true;
            }
        }

        [System.Obsolete]
        public override void PostUpdate()
        {
            if (Main.dayTime && Main.time == 0)
            {
                AgeInDays++;
            }
            int newAge = CurrentAge + 1;
            ApplyAgeEffects(newAge);
            if (++_deathCheckTimer >= DeathCheckInterval)
            {
                _deathCheckTimer = 0;
                CheckAgeDeathProbability();
            }
        }


        public override void SaveData(TagCompound tag)
        {
            tag[nameof(AgeInDays)] = AgeInDays;
            tag[nameof(HasSetAge)] = HasSetAge;
            tag[nameof(_hasShownThisSession)] = _hasShownThisSession;
        }

        public override void LoadData(TagCompound tag)
        {
            AgeInDays = tag.GetInt(nameof(AgeInDays));
            HasSetAge = tag.GetBool(nameof(HasSetAge));
            _hasShownThisSession = tag.GetBool(nameof(_hasShownThisSession));
        }

        [System.Obsolete]
        public void CheckAgeDeathProbability()
        {
            if (CurrentAge >= 130)
            {
                TriggerDeathByAge();
                return;
            }

            if (CurrentAge >= 84)
            {
                float deathChance = CalculateDeathProbability();
                if (Main.rand.NextFloat() < deathChance)
                {
                    TriggerDeathByAge();
                }
            }
        }
        public float CalculateDeathProbability()
        {
            int age = CurrentAge;
            float baseChance = 0f;
            if (age >= 84 && age < 90)
            {
                baseChance = 0.0001f;
            }
            else if (age >= 90 && age < 100)
            {
                baseChance = 0.0005f;
            }
            else if (age >= 100)
            {
                baseChance = 0.001f + (age - 100) * 0.0005f;
            }
            if (age >= 130)
            {
                return 1f;
            }
            if (Player.HasBuff(BuffID.WellFed))
            {
                baseChance *= 0.7f;
            }
            if (Player.HasBuff(BuffID.PotionSickness))
            {
                baseChance *= 1.3f;
            }
            return MathHelper.Clamp(baseChance, 0f, 0.05f);
        }

        [System.Obsolete]
        public void TriggerDeathByAge()
        {
            if (Player.whoAmI == Main.myPlayer)
            {
                Player.KillMe(PlayerDeathReason.ByCustomReason($"{Player.name}" + Language.GetTextValue("Mods.HardcoreGame.PlayerDeathReason.4")), 999999, 0);
                for (int i = 0; i < 30; i++)
                {
                    Dust.NewDustPerfect(Player.Center, DustID.Cloud, Main.rand.NextVector2Circular(3, 3), 100, Color.White, 1.5f);
                }
                SoundEngine.PlaySound(SoundID.Item123 with { Pitch = -0.5f });

                DeletePlayer();
            }

        }

        public void DeletePlayer()
        {
            string playerName = Player.name;
            string basePath = Main.PlayerPath;
            string[] extensionsToDelete = [".plr", ".plr.bak", ".tplr", ".tplr.bak"];
            foreach (string extension in extensionsToDelete)
            {
                string filePath = Path.Combine(basePath, $"{playerName}{extension}");
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
            Main.menuMode = 0;
            Main.gameMenu = true;
            Netplay.Disconnect = true;
        }

        public void ApplyAgeEffects(int newAge)
        {
            switch (newAge)
            {
                case int n when n <= 5:
                    Player.GetDamage(DamageClass.Generic) *= 0.3f;
                    Player.statLifeMax2 = (int)(Player.statLifeMax2 * 0.5f);
                    Player.moveSpeed += 0.3f;
                    break;
                case int n when n >= 6 && n <= 12:
                    Player.GetDamage(DamageClass.Generic) *= 0.7f;
                    Player.statLifeMax2 = (int)(Player.statLifeMax2 * 0.8f);
                    break;
                case int n when n >= 13 && n <= 19:
                    Player.GetCritChance(DamageClass.Generic) += 5f;
                    break;

                case int n when n >= 20 && n <= 50:
                    Player.statDefense += 5;
                    break;

                case int n when n >= 51 && n <= 80:
                    Player.statLifeMax2 = (int)(Player.statLifeMax2 * 1.2f);
                    Player.GetDamage(DamageClass.Generic) *= 0.85f;
                    Player.moveSpeed -= 0.15f;
                    break;

                case int n when n >= 81:
                    Player.statLifeMax2 = (int)(Player.statLifeMax2 * 1.5f);
                    Player.GetDamage(DamageClass.Generic) *= 0.7f;
                    Player.moveSpeed -= 0.25f;
                    break;
            }
        }
    }  
}